import { createStore } from 'vuex';
import { loginHttp } from '@/lib/http/http';
import storage from '@/lib/storage/storage';
import { IState } from "./store";
import utils from '@/lib/utils';
// 列表转树
const listToTree = (list: any[], id: string = ""): any[] => {
  if (utils.empty(list)) {
    return [];
  }
  const resArr: any[] = [];
  for (const item of list) {
    if (item.pid === id && item.is_show === 1) {
      const temItem = utils.CopyNewObject(item);
      if (utils.empty(temItem.route)) {
        temItem.route = temItem.id;
      }
      temItem.children = listToTree(list, temItem.id);
      resArr.push(temItem);
    }
  }
  return resArr;
};
export default createStore<IState>({
  state: {
    UserInfo: { account: {}, user: {} },
    UIAuth: {},
    MenuList: [],
    bodySize: {
      height: 500,
      width: 1000,
    },
  },
  mutations: {
    /**
     * 更新窗口大小
     */
    updateBodySize(state, params: any) {
      state.bodySize = params;
    },
    // 保存UI权限
    saveUIAuth(state, params: any) {
      state.UIAuth = params;
    },
    // 更新用户信息
    updateUserInfo(state, params: any) {
      state.UserInfo = params;
    },
    // 更新菜单列表
    updateMenuList(state, params: any) {
      state.MenuList = params;
    },
  },
  actions: {
    // 获取当前登录用户信息
    getLoginUserInfo({ commit }) {
      loginHttp.Get("/login").then((data) => {
        // 保存用户信息到缓存
        storage.user.Set(data.user);
        // 保存界面权限到缓存
        const uiAuthList: any = {};
        data.api.forEach((item: any) => {
          uiAuthList[item] = true;
        });
        // 保存界面权限到缓存
        storage.uiAuth.Set(uiAuthList);
        // 保存菜单列表到缓存
        storage.menuList.Set(data.auth);
        // 更新用户信息
        commit('updateUserInfo', data.user);
        // 更新UI权限
        commit('saveUIAuth', uiAuthList);
        // 更新菜单列表
        commit('updateMenuList', data.auth);

      }).catch((err) => false);
    }
  },
  getters: {
    getMenuList(state): any[] {
      return listToTree(state.MenuList);
    },
  },
});
